<template>
  <div class="profile-container">
    <!-- 左侧导航 -->
    <el-card class="nav-card">
      <div class="user-brief">
        <div class="avatar-container">
          <div class="avatar-wrapper">
            <el-avatar :size="100" :src="userAvatar" />
            <div class="avatar-overlay">
              <el-icon><Camera /></el-icon>
            </div>
          </div>
          <div class="avatar-input-wrapper">
            <el-input
              v-model="avatarUrl"
              placeholder="请输入头像图片链接"
              class="avatar-input"
            >
              <template #append>
                <el-button type="primary" @click="updateAvatar">更新</el-button>
              </template>
            </el-input>
          </div>
        </div>
        <h3>{{ profile.username }}</h3>
        <el-tag :type="profile.role === 'admin' ? 'danger' : 'success'" size="small">
          {{ profile.role === 'admin' ? '管理员' : '普通用户' }}
        </el-tag>
      </div>
      <el-menu
        :default-active="activeMenu"
        class="profile-menu"
        @select="handleMenuSelect"
      >
        <el-menu-item index="info">
          <el-icon><User /></el-icon>
          <span>个人信息</span>
        </el-menu-item>
        <el-menu-item index="favorites">
          <el-icon><Star /></el-icon>
          <span>我的收藏</span>
        </el-menu-item>
        <el-menu-item index="orders">
          <el-icon><List /></el-icon>
          <span>订单历史</span>
        </el-menu-item>
        <el-menu-item index="security">
          <el-icon><Lock /></el-icon>
          <span>账号安全</span>
        </el-menu-item>
      </el-menu>
    </el-card>

    <!-- 右侧内容区 -->
    <div class="content-area">
      <!-- 个人信息 -->
      <el-card v-show="activeMenu === 'info'" class="content-card">
        <template #header>
          <div class="card-header">
            <h3>个人信息</h3>
            <el-button type="primary" @click="updateProfile" :loading="loading">保存修改</el-button>
          </div>
        </template>
        <el-form :model="profile" label-width="100px" :disabled="loading">
          <el-form-item label="用户名">
            <el-input v-model="profile.username" disabled />
          </el-form-item>
          <el-form-item label="邮箱">
            <el-input v-model="profile.email" />
          </el-form-item>
          <el-form-item label="手机号码">
            <el-input v-model="profile.phone" />
          </el-form-item>
          <el-form-item label="收货地址">
            <el-input type="textarea" v-model="profile.address" :rows="2" />
          </el-form-item>
        </el-form>
      </el-card>

      <!-- 我的收藏 -->
      <el-card v-show="activeMenu === 'favorites'" class="content-card">
        <template #header>
          <div class="card-header">
            <h3>我的收藏</h3>
          </div>
        </template>
        <el-empty v-if="favorites.length === 0" description="暂无收藏商品" />
        <div v-else class="favorites-grid">
          <el-card v-for="item in favorites" :key="item.id" class="favorite-item" shadow="hover">
            <img :src="item.image" class="favorite-image" />
            <div class="favorite-info">
              <h4>{{ item.name }}</h4>
              <p class="price">¥{{ item.price }}</p>
              <div class="favorite-actions">
                <el-button type="primary" size="small" @click="showMedicineDetail(item)">查看详情</el-button>
                <el-button type="danger" size="small" @click="removeFavorite(item.id)">取消收藏</el-button>
              </div>
            </div>
          </el-card>
        </div>
      </el-card>

      <!-- 药品详情对话框 -->
      <el-dialog
        :title="selectedMedicine ? selectedMedicine.name : ''"
        v-model="dialogVisible"
        width="700px"
        class="detail-dialog-root"
      >
        <div v-if="selectedMedicine" class="detail-dialog">
          <div class="detail-left">
            <img :src="selectedMedicine.image" :alt="selectedMedicine.name" />
          </div>
          <div class="detail-right">
            <h2 class="detail-title">{{ selectedMedicine.name }}</h2>
            <div class="detail-price-row">
              <span class="detail-price">¥{{ selectedMedicine.price.toFixed(2) }}</span>
              <span v-if="selectedMedicine.originPrice && selectedMedicine.originPrice > selectedMedicine.price" class="detail-origin">¥{{ selectedMedicine.originPrice }}</span>
            </div>
            <div class="detail-tags">
              <el-tag size="small" type="info">类别：{{ selectedMedicine.category }}</el-tag>
              <el-tag size="small" type="success">库存：{{ selectedMedicine.stock }}件</el-tag>
              <el-tag size="small" type="warning">厂家：{{ selectedMedicine.manufacturer }}</el-tag>
              <el-tag size="small" type="">规格：{{ selectedMedicine.specification }}</el-tag>
            </div>
            <div class="detail-actions">
              <el-input-number
                v-model="purchaseQuantity"
                :min="1"
                :max="selectedMedicine.stock"
                size="small"
              />
              <el-button type="primary" @click="addToCart(selectedMedicine, purchaseQuantity)">
                加入购物车
              </el-button>
              <el-button class="fav-btn" link @click="toggleFavorite(selectedMedicine)">
                <el-icon :class="['fav-icon', isFavorited(selectedMedicine) ? 'active' : '']">
                  <component :is="isFavorited(selectedMedicine) ? StarFilled : Star" />
                </el-icon>
                <span class="fav-text" :class="{active: isFavorited(selectedMedicine)}">
                  {{ isFavorited(selectedMedicine) ? '已收藏' : '收藏' }}
                </span>
              </el-button>
            </div>
            <div class="detail-desc-card">
              <h3>产品说明</h3>
              <p>{{ selectedMedicine.description }}</p>
              <div v-if="selectedMedicine.usage" class="detail-usage">用法用量：{{ selectedMedicine.usage }}</div>
            </div>
          </div>
        </div>
      </el-dialog>

      <!-- 订单历史 -->
      <el-card v-show="activeMenu === 'orders'" class="content-card">
        <template #header>
          <div class="card-header">
            <h3>订单历史</h3>
          </div>
        </template>
        <el-tabs v-model="activeOrderTab">
          <el-tab-pane label="全部订单" name="all">
            <el-table :data="orders" style="width: 100%">
              <el-table-column prop="orderNo" label="订单号" width="180" />
              <el-table-column prop="createTime" label="下单时间" width="180" />
              <el-table-column prop="totalAmount" label="总金额" width="120">
                <template #default="scope">
                  ¥{{ scope.row.totalAmount }}
                </template>
              </el-table-column>
              <el-table-column prop="status" label="订单状态">
                <template #default="scope">
                  <el-tag :type="getOrderStatusType(scope.row.status)">
                    {{ getOrderStatusText(scope.row.status) }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column label="操作">
                <template #default="scope">
                  <el-button type="primary" link @click="viewOrderDetail(scope.row.id)">
                    查看详情
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
          <el-tab-pane label="待付款" name="unpaid" />
          <el-tab-pane label="待发货" name="unshipped" />
          <el-tab-pane label="待收货" name="shipped" />
          <el-tab-pane label="已完成" name="completed" />
        </el-tabs>
      </el-card>

      <!-- 账号安全 -->
      <el-card v-show="activeMenu === 'security'" class="content-card">
        <template #header>
          <div class="card-header">
            <h3>账号安全</h3>
          </div>
        </template>
        <el-form :model="password" label-width="100px" @submit.prevent>
          <el-form-item label="当前密码">
            <el-input v-model="password.current" type="password" show-password />
          </el-form-item>
          <el-form-item label="新密码">
            <el-input v-model="password.new" type="password" show-password />
          </el-form-item>
          <el-form-item label="确认新密码">
            <el-input v-model="password.confirm" type="password" show-password />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="changePassword" :loading="loading">修改密码</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import { computed, ref, onMounted } from 'vue'
import { useStore } from 'vuex'
import { ElMessage } from 'element-plus'
import { User, Star, List, Lock, StarFilled, Camera } from '@element-plus/icons-vue'
import axios from 'axios'
import { useRouter } from 'vue-router'

const router = useRouter()
const store = useStore()
const user = computed(() => store.state.user || { username: '', role: 'user', id: '' })
const userAvatar = computed(() => {
  if (profile.value.avatar) {
    return profile.value.avatar
  }
  return `https://api.dicebear.com/7.x/avataaars/svg?seed=${profile.value.username || 'user'}`
})

const activeMenu = ref('info')
const activeOrderTab = ref('all')
const loading = ref(false)

const profile = ref({
  id: '',
  username: '',
  role: '',
  email: '',
  phone: '',
  address: ''
})

const password = ref({
  current: '',
  new: '',
  confirm: ''
})

const favorites = ref([])
const orders = ref([])

const dialogVisible = ref(false)
const selectedMedicine = ref(null)
const purchaseQuantity = ref(1)
const avatarUrl = ref('')

// 加载用户信息
const loadUserProfile = async () => {
  if (!user.value.id) return
  loading.value = true
  try {
    const res = await axios.get(`http://localhost:3000/users/${user.value.id}`)
    profile.value = {
      ...res.data,
      address: res.data.address || ''
    }
  } catch (e) {
    ElMessage.error('获取用户信息失败')
  } finally {
    loading.value = false
  }
}

// 加载收藏列表
const loadFavorites = async () => {
  try {
    const res = await axios.get(`http://localhost:3000/users/${user.value.id}`)
    favorites.value = res.data.favorites || []
  } catch (e) {
    ElMessage.error('获取收藏列表失败')
  }
}

// 加载订单历史
const loadOrders = async () => {
  try {
    const res = await axios.get(`http://localhost:3000/users/${user.value.id}/orders`)
    // 字段适配，兼容后端字段
    orders.value = (res.data || []).map(order => ({
      ...order,
      orderNo: order.id,
      createTime: order.createdAt || order.createTime,
      totalAmount: order.totalAmount ?? order.total ?? 0
    }))
  } catch (e) {
    ElMessage.error('获取订单历史失败')
  }
}

// 更新个人信息
const updateProfile = async () => {
  loading.value = true
  try {
    await axios.put(`http://localhost:3000/users/${profile.value.id}`, profile.value)
    store.commit('SET_USER', profile.value)
    localStorage.setItem('username', profile.value.username)
    localStorage.setItem('role', profile.value.role)
    localStorage.setItem('userId', profile.value.id)
    ElMessage.success('个人信息更新成功')
  } catch (e) {
    ElMessage.error('更新失败，请重试')
  } finally {
    loading.value = false
  }
}

// 修改密码
const changePassword = async () => {
  if (password.value.new !== password.value.confirm) {
    ElMessage.error('两次输入的新密码不一致')
    return
  }
  loading.value = true
  try {
    await axios.patch(`http://localhost:3000/users/${profile.value.id}`, { password: password.value.new })
    ElMessage.success('密码修改成功')
    password.value = { current: '', new: '', confirm: '' }
  } catch (e) {
    ElMessage.error('密码修改失败，请重试')
  } finally {
    loading.value = false
  }
}

// 菜单选择处理
const handleMenuSelect = (key) => {
  activeMenu.value = key
  if (key === 'favorites') {
    loadFavorites()
  } else if (key === 'orders') {
    loadOrders()
  }
}

// 显示药品详情
const showMedicineDetail = (medicine) => {
  selectedMedicine.value = medicine
  purchaseQuantity.value = 1
  dialogVisible.value = true
}

// 添加到购物车
const addToCart = (medicine, quantity = 1) => {
  if (!store.state.isAuthenticated) {
    ElMessage.warning('请先登录后再添加商品到购物车')
    router.push('/login')
    return
  }

  const cartItem = {
    id: medicine.id,
    name: medicine.name,
    price: medicine.price,
    quantity: quantity,
    image: medicine.image
  }
  
  store.commit('ADD_TO_CART', cartItem)
  ElMessage.success('已添加到购物车')
  dialogVisible.value = false
}

// 判断商品是否已收藏
const isFavorited = (medicine) => {
  return favorites.value.some(item => item.id === medicine.id)
}

// 收藏/取消收藏
const toggleFavorite = async (medicine) => {
  if (!store.state.isAuthenticated) {
    ElMessage.warning('请先登录后再收藏商品')
    router.push('/login')
    return
  }
  let newFavorites
  if (isFavorited(medicine)) {
    newFavorites = favorites.value.filter(item => item.id !== medicine.id)
  } else {
    newFavorites = [...favorites.value, medicine]
  }
  try {
    await axios.patch(`http://localhost:3000/users/${user.value.id}`, { favorites: newFavorites })
    favorites.value = newFavorites
    ElMessage.success(isFavorited(medicine) ? '已取消收藏' : '已收藏')
  } catch (e) {
    ElMessage.error('操作失败，请重试')
  }
}

// 取消收藏
const removeFavorite = async (id) => {
  try {
    const res = await axios.get(`http://localhost:3000/users/${user.value.id}`)
    const newFavorites = (res.data.favorites || []).filter(item => item.id !== id)
    await axios.patch(`http://localhost:3000/users/${user.value.id}`, { favorites: newFavorites })
    favorites.value = newFavorites
    ElMessage.success('已取消收藏')
  } catch (e) {
    ElMessage.error('操作失败，请重试')
  }
}

// 查看订单详情
const viewOrderDetail = (id) => {
  router.push(`/orders/${id}`)
}

// 获取订单状态类型
const getOrderStatusType = (status) => {
  const types = {
    unpaid: 'warning',
    unshipped: 'info',
    shipped: 'primary',
    completed: 'success',
    cancelled: 'danger'
  }
  return types[status] || 'info'
}

// 获取订单状态文本
const getOrderStatusText = (status) => {
  const texts = {
    unpaid: '待付款',
    unshipped: '待发货',
    shipped: '待收货',
    completed: '已完成',
    cancelled: '已取消'
  }
  return texts[status] || status
}

// 更新头像
const updateAvatar = async () => {
  if (!avatarUrl.value) {
    ElMessage.warning('请输入头像图片链接')
    return
  }

  try {
    // 更新用户头像
    await axios.patch(`http://localhost:3000/users/${profile.value.id}`, {
      avatar: avatarUrl.value
    })
    profile.value.avatar = avatarUrl.value
    avatarUrl.value = '' // 清空输入框
    ElMessage.success('头像更新成功')
  } catch (error) {
    ElMessage.error('头像更新失败')
  }
}

onMounted(() => {
  loadUserProfile()
})
</script>

<style scoped>
.profile-container {
  display: flex;
  gap: 24px;
  max-width: 1200px;
  margin: 40px auto;
  padding: 0 20px;
}

.nav-card {
  width: 240px;
  flex-shrink: 0;
}

.user-brief {
  text-align: center;
  padding: 20px 0;
}

.user-brief h3 {
  margin: 12px 0 8px;
  font-size: 18px;
}

.profile-menu {
  border-right: none;
}

.content-area {
  flex: 1;
}

.content-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h3 {
  margin: 0;
  font-size: 18px;
}

.favorites-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 20px;
  padding: 20px 0;
}

.favorite-item {
  transition: transform 0.3s;
}

.favorite-item:hover {
  transform: translateY(-5px);
}

.favorite-image {
  width: 100%;
  height: 200px;
  object-fit: cover;
  border-radius: 4px;
}

.favorite-info {
  padding: 12px 0;
}

.favorite-info h4 {
  margin: 0 0 8px;
  font-size: 16px;
}

.price {
  color: #f56c6c;
  font-size: 18px;
  font-weight: bold;
  margin: 8px 0;
}

.favorite-actions {
  display: flex;
  gap: 8px;
  margin-top: 12px;
}

.detail-dialog-root :deep(.el-dialog__body) {
  padding: 0 32px 32px 32px;
  background: #f8fafb;
  border-radius: 18px;
}

.detail-dialog {
  display: flex;
  gap: 32px;
  align-items: flex-start;
}

.detail-left {
  flex: 0 0 260px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #fff;
  border-radius: 14px;
  box-shadow: 0 2px 12px rgba(64,158,255,0.08);
  padding: 24px;
  min-height: 320px;
}

.detail-left img {
  max-width: 200px;
  max-height: 260px;
  object-fit: contain;
  border-radius: 10px;
  background: #f6faff;
}

.detail-right {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.detail-title {
  font-size: 26px;
  font-weight: 700;
  color: #303133;
  margin-bottom: 4px;
}

.detail-price-row {
  display: flex;
  align-items: baseline;
  gap: 12px;
  margin-bottom: 8px;
}

.detail-price {
  color: #409EFF;
  font-size: 24px;
  font-weight: 700;
}

.detail-origin {
  color: #bbb;
  font-size: 16px;
  text-decoration: line-through;
}

.detail-tags {
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
  margin-bottom: 8px;
}

.detail-actions {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 8px;
}

.detail-desc-card {
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(64,158,255,0.06);
  padding: 18px 16px 10px 16px;
  margin-top: 8px;
}

.detail-desc-card h3 {
  font-size: 17px;
  color: #409EFF;
  margin-bottom: 8px;
}

.detail-desc-card p {
  color: #606266;
  font-size: 15px;
  margin-bottom: 6px;
}

.detail-usage {
  color: #909399;
  font-size: 14px;
  margin-top: 4px;
}

.fav-icon {
  font-size: 20px;
  color: #bbb;
  transition: color 0.2s, transform 0.2s;
}

.fav-icon.active {
  color: #409EFF;
  transform: scale(1.1);
}

.fav-text {
  color: #909399;
  transition: color 0.2s;
}

.fav-text.active {
  color: #409EFF;
}

@media (max-width: 700px) {
  .detail-dialog {
    flex-direction: column;
    gap: 16px;
  }
  .detail-left {
    min-height: 180px;
    padding: 12px;
    max-width: 100%;
  }
  .detail-left img {
    max-width: 100%;
    max-height: 180px;
  }
}

.avatar-container {
  position: relative;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 16px;
  padding: 20px 0;
}

.avatar-wrapper {
  position: relative;
  cursor: pointer;
  border-radius: 50%;
  overflow: hidden;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.avatar-wrapper:hover {
  transform: scale(1.05);
}

.avatar-wrapper:hover .avatar-overlay {
  opacity: 1;
}

.avatar-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  opacity: 0;
  transition: opacity 0.3s ease;
}

.avatar-overlay .el-icon {
  color: white;
  font-size: 24px;
}

.avatar-input-wrapper {
  width: 100%;
  padding: 0 20px;
}

.avatar-input {
  width: 100%;
}

.avatar-input :deep(.el-input__wrapper) {
  border-radius: 20px;
}

.avatar-input :deep(.el-input-group__append) {
  padding: 0 15px;
  background: var(--el-color-primary);
  border: none;
  border-radius: 0 20px 20px 0;
}

.avatar-input :deep(.el-input-group__append .el-button) {
  color: white;
  border: none;
  padding: 0 10px;
}

.avatar-input :deep(.el-input-group__append .el-button:hover) {
  background: transparent;
  opacity: 0.9;
}
</style>